package com.minesweeper.tools;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

/**
 * @author skniy
 */
public class GameMusic implements Runnable {

    /**
     * 音乐文件
     */
    private File musicFile;
    /**
     * 是否播放
     */
    private boolean playFlag;

    /**
     * 构造方法
     *
     * @param musicFile
     */
    public GameMusic(File musicFile) {
        this.musicFile = musicFile;
        this.playFlag = false;
    }

    @Override
    public void run() {
        while (true) {
            if (playFlag) {
                //打开文件
                AudioInputStream audioInputStream = null;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(musicFile);
                } catch (UnsupportedAudioFileException | IOException e) {
                    e.printStackTrace();
                }
                assert audioInputStream != null;
                AudioFormat audioFormat = audioInputStream.getFormat();
                SourceDataLine sourceDataLine = null;
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
                try {
                    sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                }
                try {
                    assert sourceDataLine != null;
                    sourceDataLine.open(audioFormat);
                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                }
                sourceDataLine.start();
                //播放音乐
                int nBytesRead = 0;
                byte[] abData = new byte[512];
                while (nBytesRead != -1) {
                    try {
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (nBytesRead >= 0) {
                        sourceDataLine.write(abData, 0, nBytesRead);
                    }
                }
                //关闭SourceDataLine
                sourceDataLine.drain();
                sourceDataLine.close();
                playFlag = false;
            } else {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 播放音乐
     */
    public void playMusic() {
        this.playFlag = true;
    }

}
